import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  OnDestroy,
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { combineLatest, forkJoin } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import {
  AlbumArgs,
  AlbumService,
  AlbumsInfo,
  CategoryInfo,
} from '../../services/apis/album.service';
import { AlbumInfo, MetaData, MetaValue, SubCategory } from '../../services/apis/types';
import { CategoryService } from '../../services/business/category.service';
import { PlayerService } from '../../services/business/player.service';
import { PageService } from '../../services/tools/page.service';
interface CheckedMeta {
  metaRowId: number;
  metaRowName: string;
  metaId: number;
  metaName: string;
}
@Component({
  selector: 'app-albums',
  templateUrl: './albums.component.html',
  styleUrls: ['./albums.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AlbumsComponent implements OnInit, OnDestroy {
  total = 0;
  searchParams: AlbumArgs = {
    category: '',
    subcategory: '',
    meta: '',
    sort: 0,
    page: 1,
    perPage: 30,
  };
  categoryInfo: CategoryInfo;
  checkedMetas: CheckedMeta[] = [];
  albumsInfo: AlbumsInfo;
  sorts = ['综合排序', '最近更新', '播放最多'];
  currentIcon = 'headset';
  constructor(
    private albumsServe: AlbumService,
    private cdr: ChangeDetectorRef,
    private route: ActivatedRoute,
    private categoryServe: CategoryService,
    private router: Router,
    private playService: PlayerService,
    private pageService: PageService
  ) {}
  ngOnDestroy(): void {
    this.clearSubCategory();
  }

  ngOnInit(): void {
    this.route.paramMap
      .pipe(withLatestFrom(this.categoryServe.getCategory()))
      .subscribe(([paramMap, category]) => {
        const pinyin = paramMap.get('pinyin');
        this.searchParams.category = pinyin;
        if (pinyin !== category) {
          this.categoryServe.setCategory(pinyin);
        }
        this.searchParams.category = pinyin;
        this.searchParams.subcategory = '';
        this.categoryServe.setSubCategory([]);
        this.unCheckMeat('clear');
        this.updatePageData();
      });
      this.pageService.setPageInfo("专辑列表", "angular10防喜马拉雅", "小说，音乐");
  }
  //播放全部
  playAlbum(event: MouseEvent, albumId: number): void {
    event.stopPropagation();
    this.albumsServe
      .album(albumId.toString())
      .subscribe(({ mainInfo, albumId, tracksInfo }) => {
        this.playService.setTracks(tracksInfo.tracks);
        this.playService.setCurrentIndex(0);
        this.playService.setAlbum({ ...mainInfo, albumId });
      });
    // this.playService.setTracks(this.tracks);
    // this.playService.setCurrentIndex(0);
    // this.playService.setAlbum(this.albumInfo);
  }
  changeSubCateory(subCateory?: SubCategory): void {
    console.log(subCateory);
    if (this.searchParams.subcategory != subCateory?.code) {
      this.searchParams.subcategory = subCateory?.code || '';
      this.categoryServe.setSubCategory([subCateory.displayValue]);
      this.unCheckMeat('clear');
      this.updatePageData();
    }
  }
  changeSort(index: number): void {
    if (this.searchParams.sort != index) {
      this.searchParams.sort = index;
      this.updateAlbums();
    }
  }
  private updatePageData(): void {
    forkJoin([
      this.albumsServe.albums(this.searchParams),
      this.albumsServe.detailCategoryPageInfo(this.searchParams),
    ]).subscribe(([albumsInfo, categoryInfo]) => {
      this.categoryInfo = categoryInfo;
      this.albumsInfo = albumsInfo;
      this.total = albumsInfo.total;
      this.cdr.markForCheck();
    });
  }
  private updateAlbums(): void {
    this.albumsServe.albums(this.searchParams).subscribe((albumsInfo) => {
      this.albumsInfo = albumsInfo;
      this.cdr.markForCheck();
      this.total = albumsInfo.total;
    });
  }
  private changeMeta(row: MetaData, meta: MetaValue) {
    console.log(row, meta);
    this.checkedMetas.push({
      metaRowId: row.id,
      metaRowName: row.name,
      metaId: meta.id,
      metaName: meta.displayName,
    });
    this.searchParams.meta = this.getMetaParams();
    this.updateAlbums();
  }
  private showMetaRow(name: string): boolean {
    if (this.checkedMetas.length) {
      return (
        this.checkedMetas.findIndex((item) => item.metaRowName == name) === -1
      );
    }
    return true;
  }
  private unCheckMeat(meta: CheckedMeta | 'clear'): void {
    if (meta == 'clear') {
      this.checkedMetas = [];
      this.searchParams.meta = '';
    } else {
      const targetIndex = this.checkedMetas.findIndex((item) => {
        return (
          item.metaRowName == meta.metaRowName && item.metaId == meta.metaId
        );
      });
      if (targetIndex > -1) {
        this.checkedMetas.splice(targetIndex, 1);
        this.searchParams.meta = this.getMetaParams();
      }
    }
    this.updateAlbums();
  }
  private getMetaParams(): string {
    let result = '';
    if (this.checkedMetas.length) {
      this.checkedMetas.forEach((item) => {
        result += item.metaRowId + '_' + item.metaId + '_';
      });
    }
    return result.slice(0, -1);
  }
  trackBySubCategory(index: number, item: SubCategory): string {
    return item.code;
  }
  trackByMetas(index: number, item: MetaValue): number {
    return item.id;
  }
  changePage(newPageNum: number): void {
    console.log(newPageNum);
    if (this.searchParams.page != newPageNum) {
      this.searchParams.page = newPageNum;
      this.updateAlbums();
    }
  }
  private clearSubCategory(): void {
    this.searchParams.subcategory = '';
    this.categoryServe.setSubCategory([]);
  }
}
